package com.dc.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentMap<String, WebSocketServer> cumap = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;


    //接收sid
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:" + sid + ",当前在线人数为" + getOnlineCount());
        this.sid = sid;
        cumap.put(sid, this);
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        cumap.remove(sid);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + sid + "的信息:" + message);
        //群发消息
        try {
            WebSocketServer webSocketServer = cumap.get(sid);
            webSocketServer.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     */
    public void sendInfo(String message) {

        log.info("群发消息" + "，推送内容:" + message);
        for (WebSocketServer value : cumap.values()) {
            try {
                value.sendMessage(message);
            } catch (IOException e) {
                continue;
            }

        }
    }


    /**
     * 推送消息给指定的用户列表
     *
     * @param message 消息内容
     * @param sidList 用户id列表
     */
    public void sendInfoToList(String message, List<String> sidList) {
        try {
            if (CollectionUtils.isEmpty(sidList)) {
                return;
            }
            // 已发送的sid集合
            List<String> sendSidList = new ArrayList<>();
            for (Map.Entry<String, WebSocketServer> m : cumap.entrySet()) {
                if (sidList.contains(m.getKey())) {
                    try {
                        m.getValue().sendMessage(message);
                        sendSidList.add(m.getKey());
                    } catch (IOException e) {
                        log.error("消息推送失败:{}", e.getMessage());
                        sendSidList.add(m.getKey());
                    }
                }
                if (sendSidList.size() == sidList.size()) {
                    // 全部推送完毕，则跳出循环
                    break;
                }
            }
        } catch (Exception e) {
            log.error("推送消息给指定的用户列表-异常", e);
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
